package spring.chatroom.java_chatroom.controller;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.socket.WebSocketSession;
import spring.chatroom.java_chatroom.common.constant.Constants;
import spring.chatroom.java_chatroom.common.constant.VerifyHtml;
import spring.chatroom.java_chatroom.common.utils.*;
import spring.chatroom.java_chatroom.mapper.ChatInfoMapper;
import spring.chatroom.java_chatroom.mapper.UserMapper;
import spring.chatroom.java_chatroom.pojo.model.ChatInfo;
import spring.chatroom.java_chatroom.pojo.model.SessionId;
import spring.chatroom.java_chatroom.pojo.model.UserInfo;
import spring.chatroom.java_chatroom.pojo.response.Response;
import spring.chatroom.java_chatroom.server.UserServer;

import java.io.IOException;
import java.util.Map;
import java.util.Random;

@Slf4j
@RestController
@RequestMapping("login")
public class LoginController {
    @Autowired
    UserServer userServer;
    @Autowired
    ChatInfoMapper chatInfoMapper;
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    MailUtil mailUtil;
    @Autowired
    private UserMapper userMapper;

    //注册 用户名不能重复
    @RequestMapping("/register")
    public Response register(String username, String password) {
        log.info("register 用户注册 {}", username);
        try {
            password = SecurityUtil.encrypt(password);

            UserInfo UserInfo = new UserInfo(username, password);

            UserInfo u = userServer.register(UserInfo);

            if(u.getUserId() == 0) {
                throw new RuntimeException("用户名重复: " + username);
            }

            u.setPassword("");

            initSomeBody(u);

            return Response.success(Map.of("status", "success"));
        } catch (Exception e) {
            e.printStackTrace();
            return Response.success(Map.of("status", "fail", "msg", e.getMessage()));
        }
    }

    //    使用名字密码
    @RequestMapping("byUP")
    public Response byUP(@NotNull String username, @NotNull String password, HttpServletRequest request, HttpServletResponse response) throws IOException {
        log.info("用户密码登录 ip={} | username={} | password={}", request.getRemoteAddr(), username, password);

        UserInfo user = new UserInfo(username, password);

        //验证用户是否存在
        UserInfo userInfo = userServer.getUserInfoByName(username);

        if (userInfo == null) {
            return Response.success(Map.of("status", "fail", "msg", "用户名错误"));
        }

        if (!SecurityUtil.verify(password, userInfo.getPassword())) {
            return Response.success(Map.of("status", "fail", "msg", "密码错误"));
        }

        //如果没有就创建一个新的会话
        HttpSession session = request.getSession(true);

        //判断下是否登录了
        WebSocketSession attribute = WebSocketSessionManagerUtil.getAttribute(userInfo.getUserId());

        //是这里把我的ai的session个删掉
        if (attribute != null) {
            //那么就是登录了 移除上一个登录的session和websocket
            WebSocketSessionManagerUtil.removeAttribute(userInfo.getUserId());
            attribute.close();
        }

        session.setAttribute("user", userInfo);

        //将密码给重置了
        userInfo.setPassword("");

        //设置JWT cookie
        setCookie(response, userInfo);

        return Response.success(Map.of("status", "success", "msg", userInfo.getUserId()));
    }

    private void setCookie(HttpServletResponse response, Object userInfo) {
        String s = JWTUtil.getToken(userInfo);

        Cookie cookie = new Cookie("jwt-token", s);

        cookie.setMaxAge(7 * 24 * 60 * 60); //7天过期

        cookie.setPath("/");

        response.addCookie(cookie);
    }

    /**
     * 使用邮箱登录
     */
    @RequestMapping("email")
    public Response email(@NotNull String email, @NotNull String code, HttpServletRequest request, HttpServletResponse response) {
        log.info("用户邮箱登录 email={} | code={}", email, code);

        String s = redisUtil.get("login" + email);

        if(s == null) {
            return Response.success(Map.of("status", "fail", "msg", "该邮箱未被使用"));
        }

        if(s.equals(Constants.REDIS_ERROR)){
            return Response.success(Map.of("status", "fail"));
        }

        if (s.isEmpty()) {
            return Response.success(Map.of("status", "fail", "msg", "邮箱错误"));
        }
        if (!s.equals(code)) {
            return Response.success(Map.of("status", "fail", "msg", "验证码错误"));
        }

        UserInfo user = userMapper.getUserInfoByEmail(email);

        //获取到当前会话的session
        HttpSession session = request.getSession(true);

        session.setAttribute("user", user);

        //设置JWT cookie
        setCookie(response, Map.of("EmailToken",user.getUserId() + email));

        return Response.success(Map.of("status", "success", "msg", user.getUserId()));
    }

    @RequestMapping("loginSomebody")
    public Map<String, String> loginSomebody(HttpServletRequest request) {
        log.info("某人登录了，正在初始化");

        UserInfo user = new UserInfo();

        user.setUserId(0);

        user.setUserName("某人");

        return Map.of("status", "success");
    }

    @RequestMapping("getCode")
    public Response getCode(@NotNull String email) {
        log.info("获取登录验证码  email={}", email);

        if (!RegexUtil.checkMail(email)) {
            return Response.success(Map.of("status", "fail", "msg", "邮箱格式不对"));
        }

        if(userMapper.getUserInfoByEmail(email) == null) {
            return Response.success(Map.of("status", "fail", "msg", "该邮箱错误"));
        }

        StringBuilder code1 = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            code1.append(random.nextInt(10));
        }

        String code = code1.toString();

        mailUtil.sendHtmlMail(email, "登录网页聊天", VerifyHtml.setLoginHtml(code));

        redisUtil.set("login" + email, code);

        return Response.success(Map.of("status", "success", "code", code));
    }

    private void initSomeBody(UserInfo u) {

        log.info("初始化 SomeBody {}", u.toString());
        //给每个用户添加某人 userId = 0
        SessionId SessionId = userServer.addFriends(u.getUserId(), 0);

        ChatInfo c = new ChatInfo();
        c.setSessionId(SessionId.getId());
        c.setUserId(0);
        c.setContent("你好呀，我是deepseek r1:7b 某人，我一直都在哦 ξ( ✿＞◡❛)");
        chatInfoMapper.insertInfo(c);
    }
}
